<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-7xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">Web Animations API</h1>
        <p class="text-gray-300 text-lg">
          使用 JavaScript 精确控制复杂动画，实现流畅的交互效果
        </p>
      </div>

      <!-- 浏览器支持提示 -->
      <div v-if="!isSupported" class="tech-card mb-8 border-yellow-600">
        <div class="flex items-center mb-4">
          <i class="i-carbon-warning text-yellow-500 text-xl mr-3"></i>
          <h3 class="text-xl font-semibold text-yellow-500">浏览器支持提示</h3>
        </div>
        <p class="text-gray-300">
          您的浏览器不完全支持 Web Animations API。建议使用最新版本的现代浏览器。
        </p>
      </div>

      <!-- 基础动画控制 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">基础动画控制</h2>
        
        <div class="bg-gray-800 rounded-lg p-8 mb-6 flex items-center justify-center min-h-[300px]">
          <div
            ref="basicBox"
            class="w-32 h-32 bg-gradient-to-br from-blue-500 to-purple-500 rounded-lg shadow-lg"
          ></div>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-4">
          <button
            @click="playBasicAnimation"
            class="tech-button"
          >
            <i class="i-carbon-play-filled mr-2"></i>
            播放
          </button>

          <button
            @click="pauseBasicAnimation"
            class="bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-pause-filled mr-2"></i>
            暂停
          </button>

          <button
            @click="reverseBasicAnimation"
            class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-reset mr-2"></i>
            反向
          </button>

          <button
            @click="cancelBasicAnimation"
            class="bg-red-600 hover:bg-red-700 text-white px-4 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-stop-filled mr-2"></i>
            取消
          </button>
        </div>

        <div class="bg-gray-800 rounded-lg p-4">
          <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
            <div>
              <div class="text-gray-400 text-sm mb-1">状态</div>
              <div class="text-white font-semibold">{{ basicAnimState }}</div>
            </div>
            <div>
              <div class="text-gray-400 text-sm mb-1">进度</div>
              <div class="text-white font-semibold">{{ basicAnimProgress }}%</div>
            </div>
            <div>
              <div class="text-gray-400 text-sm mb-1">播放速率</div>
              <div class="text-white font-semibold">{{ basicPlaybackRate }}x</div>
            </div>
            <div>
              <div class="text-gray-400 text-sm mb-1">当前时间</div>
              <div class="text-white font-semibold">{{ basicCurrentTime }}ms</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 缓动函数对比 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">缓动函数对比</h2>
        
        <div class="space-y-4 mb-6">
          <div v-for="easing in easingFunctions" :key="easing.name" class="bg-gray-800 rounded-lg p-4">
            <div class="flex items-center justify-between mb-3">
              <div>
                <h4 class="text-white font-semibold">{{ easing.name }}</h4>
                <p class="text-gray-400 text-sm">{{ easing.description }}</p>
              </div>
              <code class="text-tech-accent text-xs bg-gray-900 px-2 py-1 rounded">{{ easing.value }}</code>
            </div>
            <div class="relative h-12 bg-gray-900 rounded-lg overflow-hidden">
              <div
                :ref="el => { if (el) easingBoxes[easing.name] = el as HTMLElement }"
                class="absolute left-0 top-1/2 -translate-y-1/2 w-10 h-10 rounded-lg bg-gradient-to-br from-tech-accent to-blue-500"
              ></div>
            </div>
          </div>
        </div>

        <button
          @click="runEasingComparison"
          class="tech-button w-full"
        >
          <i class="i-carbon-play-filled mr-2"></i>
          运行对比动画
        </button>
      </div>

      <!-- 关键帧动画 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">关键帧动画</h2>
        
        <div class="bg-gray-800 rounded-lg p-8 mb-6">
          <div class="flex items-center justify-around flex-wrap gap-4">
            <div
              ref="bounceBox"
              class="w-20 h-20 bg-gradient-to-br from-green-400 to-emerald-500 rounded-full"
            ></div>
            <div
              ref="spinBox"
              class="w-20 h-20 bg-gradient-to-br from-red-400 to-pink-500 rounded-lg"
            ></div>
            <div
              ref="pulseBox"
              class="w-20 h-20 bg-gradient-to-br from-yellow-400 to-orange-500 rounded-full"
            ></div>
            <div
              ref="slideBox"
              class="w-20 h-20 bg-gradient-to-br from-purple-400 to-indigo-500 rounded-lg"
            ></div>
          </div>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
          <button
            @click="runBounceAnimation"
            class="bg-green-600 hover:bg-green-700 text-white px-4 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-arrow-down mr-2"></i>
            弹跳
          </button>

          <button
            @click="runSpinAnimation"
            class="bg-red-600 hover:bg-red-700 text-white px-4 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-rotate-360 mr-2"></i>
            旋转
          </button>

          <button
            @click="runPulseAnimation"
            class="bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-radio-button mr-2"></i>
            脉冲
          </button>

          <button
            @click="runSlideAnimation"
            class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-arrow-right mr-2"></i>
            滑动
          </button>
        </div>
      </div>

      <!-- 序列动画 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">序列动画</h2>
        
        <div class="bg-gray-800 rounded-lg p-8 mb-6">
          <div class="flex items-center justify-center gap-4">
            <div
              v-for="i in 5"
              :key="i"
              :ref="el => { if (el) sequenceBoxes[i - 1] = el as HTMLElement }"
              class="w-16 h-16 rounded-lg bg-gradient-to-br from-cyan-400 to-blue-500"
            ></div>
          </div>
        </div>

        <div class="flex gap-3">
          <button
            @click="runSequenceAnimation"
            class="tech-button flex-1"
          >
            <i class="i-carbon-play-filled mr-2"></i>
            播放序列
          </button>

          <button
            @click="runStaggerAnimation"
            class="bg-purple-600 hover:bg-purple-700 text-white px-6 py-3 rounded-lg transition-colors flex-1"
          >
            <i class="i-carbon-layers mr-2"></i>
            错峰动画
          </button>
        </div>
      </div>

      <!-- 路径动画 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">路径动画</h2>
        
        <div class="bg-gray-800 rounded-lg p-8 mb-6 relative" style="height: 400px;">
          <svg class="absolute inset-0 w-full h-full" viewBox="0 0 800 400">
            <path
              d="M 50,200 Q 200,50 400,200 T 750,200"
              stroke="#3b82f6"
              stroke-width="2"
              fill="none"
              stroke-dasharray="5,5"
            />
            <circle
              ref="pathCircle"
              cx="50"
              cy="200"
              r="20"
              fill="url(#gradient1)"
            />
            <defs>
              <linearGradient id="gradient1" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:#f59e0b;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#ef4444;stop-opacity:1" />
              </linearGradient>
            </defs>
          </svg>
        </div>

        <div class="flex gap-3">
          <button
            @click="runPathAnimation"
            class="tech-button flex-1"
          >
            <i class="i-carbon-play-filled mr-2"></i>
            沿路径运动
          </button>

          <button
            @click="runCirclePathAnimation"
            class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg transition-colors flex-1"
          >
            <i class="i-carbon-radio-button mr-2"></i>
            圆形路径
          </button>
        </div>
      </div>

      <!-- 交互动画 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">交互动画</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div
            @mouseenter="onCardHover"
            @mouseleave="onCardLeave"
            ref="hoverCard"
            class="bg-gradient-to-br from-blue-600 to-cyan-500 rounded-lg p-6 cursor-pointer"
          >
            <i class="i-carbon-cursor-1 text-4xl text-white mb-3 block"></i>
            <h3 class="text-xl font-bold text-white mb-2">悬停效果</h3>
            <p class="text-blue-100 text-sm">鼠标悬停查看动画</p>
          </div>

          <div
            @click="onCardClick"
            ref="clickCard"
            class="bg-gradient-to-br from-purple-600 to-pink-500 rounded-lg p-6 cursor-pointer"
          >
            <i class="i-carbon-touch-1 text-4xl text-white mb-3 block"></i>
            <h3 class="text-xl font-bold text-white mb-2">点击效果</h3>
            <p class="text-purple-100 text-sm">点击查看动画</p>
          </div>

          <div
            @mousedown="onCardPress"
            @mouseup="onCardRelease"
            @mouseleave="onCardRelease"
            ref="pressCard"
            class="bg-gradient-to-br from-green-600 to-emerald-500 rounded-lg p-6 cursor-pointer"
          >
            <i class="i-carbon-touch-2 text-4xl text-white mb-3 block"></i>
            <h3 class="text-xl font-bold text-white mb-2">按压效果</h3>
            <p class="text-green-100 text-sm">按住查看动画</p>
          </div>
        </div>
      </div>

      <!-- 粒子动画 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">粒子动画系统</h2>
        
        <div
          ref="particleContainer"
          @click="createParticles"
          class="bg-gray-800 rounded-lg p-8 cursor-pointer relative overflow-hidden"
          style="height: 300px;"
        >
          <div class="text-center text-gray-400">
            <i class="i-carbon-cursor-1 text-4xl mb-3 block"></i>
            <p>点击任意位置创建粒子爆炸效果</p>
          </div>
        </div>

        <div class="mt-4 bg-gray-800 rounded-lg p-4">
          <div class="flex justify-between items-center">
            <span class="text-gray-300">活跃粒子数量</span>
            <span class="text-2xl font-bold text-tech-accent">{{ activeParticles }}</span>
          </div>
        </div>
      </div>

      <!-- 动画组合 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">复杂动画组合</h2>
        
        <div class="bg-gray-800 rounded-lg p-8 mb-6 relative overflow-hidden" style="height: 400px;">
          <div
            ref="complexBox"
            class="absolute w-24 h-24 bg-gradient-to-br from-pink-500 to-rose-500 rounded-lg shadow-lg"
            style="left: 50%; top: 50%; transform: translate(-50%, -50%);"
          ></div>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-3 gap-3">
          <button
            @click="runComplexAnimation1"
            class="tech-button"
          >
            <i class="i-carbon-play-filled mr-2"></i>
            组合动画 1
          </button>

          <button
            @click="runComplexAnimation2"
            class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-play-filled mr-2"></i>
            组合动画 2
          </button>

          <button
            @click="runComplexAnimation3"
            class="bg-green-600 hover:bg-green-700 text-white px-4 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-play-filled mr-2"></i>
            组合动画 3
          </button>
        </div>
      </div>

      <!-- 文字动画 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">文字动画效果</h2>
        
        <div class="bg-gray-800 rounded-lg p-8 mb-6">
          <h3
            ref="textAnimation"
            class="text-4xl font-bold text-white text-center"
          >
            Web Animations API
          </h3>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
          <button
            @click="runTextAnimation('wave')"
            class="tech-button"
          >
            <i class="i-carbon-wave mr-2"></i>
            波浪
          </button>

          <button
            @click="runTextAnimation('bounce')"
            class="bg-green-600 hover:bg-green-700 text-white px-4 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-arrow-down mr-2"></i>
            弹跳
          </button>

          <button
            @click="runTextAnimation('fade')"
            class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-view mr-2"></i>
            淡入
          </button>

          <button
            @click="runTextAnimation('scale')"
            class="bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-zoom-in mr-2"></i>
            缩放
          </button>
        </div>
      </div>

      <!-- 动画统计 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">动画统计与性能</h2>
        
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div class="bg-gray-800 rounded-lg p-6 text-center">
            <div class="text-3xl font-bold text-blue-400 mb-2">{{ totalAnimations }}</div>
            <div class="text-gray-400 text-sm">总动画数</div>
          </div>

          <div class="bg-gray-800 rounded-lg p-6 text-center">
            <div class="text-3xl font-bold text-green-400 mb-2">{{ runningAnimations }}</div>
            <div class="text-gray-400 text-sm">运行中</div>
          </div>

          <div class="bg-gray-800 rounded-lg p-6 text-center">
            <div class="text-3xl font-bold text-yellow-400 mb-2">{{ finishedAnimations }}</div>
            <div class="text-gray-400 text-sm">已完成</div>
          </div>

          <div class="bg-gray-800 rounded-lg p-6 text-center">
            <div class="text-3xl font-bold text-purple-400 mb-2">{{ averageFrameRate }}</div>
            <div class="text-gray-400 text-sm">平均帧率</div>
          </div>
        </div>
      </div>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>Chrome 36+, Firefox 48+, Safari 13.1+, Edge 79+</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">核心 API</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">element.animate(keyframes, options)</code> - 创建动画</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">animation.play()</code> - 播放动画</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">animation.pause()</code> - 暂停动画</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">animation.reverse()</code> - 反向播放</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">animation.cancel()</code> - 取消动画</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">animation.finish()</code> - 跳到结束</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">动画属性</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li><code class="bg-gray-800 px-1 rounded">playState</code> - 播放状态（idle, running, paused, finished）</li>
              <li><code class="bg-gray-800 px-1 rounded">playbackRate</code> - 播放速率（1 = 正常速度）</li>
              <li><code class="bg-gray-800 px-1 rounded">currentTime</code> - 当前时间（毫秒）</li>
              <li><code class="bg-gray-800 px-1 rounded">startTime</code> - 开始时间</li>
              <li><code class="bg-gray-800 px-1 rounded">progress</code> - 进度（0-1）</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">关键帧格式</h4>
            <pre class="bg-gray-800 p-4 rounded text-sm overflow-x-auto">
<span class="text-gray-500">// 数组格式</span>
element.animate([
  { transform: <span class="text-green-400">'translateX(0)'</span>, opacity: <span class="text-orange-400">1</span> },
  { transform: <span class="text-green-400">'translateX(100px)'</span>, opacity: <span class="text-orange-400">0</span> }
], { duration: <span class="text-orange-400">1000</span> });

<span class="text-gray-500">// 对象格式（带偏移量）</span>
element.animate({
  transform: [<span class="text-green-400">'scale(1)'</span>, <span class="text-green-400">'scale(1.5)'</span>, <span class="text-green-400">'scale(1)'</span>],
  offset: [<span class="text-orange-400">0</span>, <span class="text-orange-400">0.5</span>, <span class="text-orange-400">1</span>]
}, { duration: <span class="text-orange-400">1000</span> });</pre>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">动画选项</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li><code class="bg-gray-800 px-1 rounded">duration</code> - 持续时间（毫秒）</li>
              <li><code class="bg-gray-800 px-1 rounded">delay</code> - 延迟（毫秒）</li>
              <li><code class="bg-gray-800 px-1 rounded">iterations</code> - 重复次数（Infinity = 无限）</li>
              <li><code class="bg-gray-800 px-1 rounded">direction</code> - 方向（normal, reverse, alternate, alternate-reverse）</li>
              <li><code class="bg-gray-800 px-1 rounded">easing</code> - 缓动函数（linear, ease, ease-in, ease-out, ease-in-out, cubic-bezier()）</li>
              <li><code class="bg-gray-800 px-1 rounded">fill</code> - 填充模式（none, forwards, backwards, both）</li>
              <li><code class="bg-gray-800 px-1 rounded">endDelay</code> - 结束延迟</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">事件监听</h4>
            <pre class="bg-gray-800 p-4 rounded text-sm overflow-x-auto">
<span class="text-blue-400">const</span> animation = element.animate(keyframes, options);

<span class="text-gray-500">// 动画完成</span>
animation.finished.then(<span class="text-blue-400">()</span> <span class="text-blue-400">=></span> {
  console.log(<span class="text-green-400">'动画完成'</span>);
});

<span class="text-gray-500">// 监听事件</span>
animation.onfinish = <span class="text-blue-400">()</span> <span class="text-blue-400">=></span> {
  console.log(<span class="text-green-400">'动画结束'</span>);
};

animation.oncancel = <span class="text-blue-400">()</span> <span class="text-blue-400">=></span> {
  console.log(<span class="text-green-400">'动画取消'</span>);
};</pre>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>UI 交互动画（按钮、卡片、菜单等）</li>
              <li>页面过渡效果</li>
              <li>数据可视化动画</li>
              <li>游戏开发</li>
              <li>加载指示器和进度条</li>
              <li>粒子系统</li>
              <li>SVG 动画</li>
              <li>滚动驱动的动画</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">优势</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li><strong>性能优异：</strong>在独立线程运行，不阻塞主线程</li>
              <li><strong>精确控制：</strong>可以暂停、恢复、反向、调速</li>
              <li><strong>同步管理：</strong>多个动画可以精确同步</li>
              <li><strong>Promise 支持：</strong>便于处理异步动画序列</li>
              <li><strong>CSS 兼容：</strong>可以使用 CSS 属性和缓动函数</li>
              <li><strong>内存友好：</strong>自动清理完成的动画</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">与 CSS 动画对比</h4>
            <div class="text-sm space-y-2">
              <p><strong>Web Animations API：</strong></p>
              <ul class="list-disc list-inside ml-4">
                <li>JavaScript 控制，更灵活</li>
                <li>可以动态修改参数</li>
                <li>支持 Promise</li>
                <li>可以精确控制播放状态</li>
              </ul>
              <p><strong>CSS 动画：</strong></p>
              <ul class="list-disc list-inside ml-4">
                <li>声明式，代码更简洁</li>
                <li>浏览器优化更好</li>
                <li>适合简单的重复动画</li>
                <li>便于维护和复用</li>
              </ul>
            </div>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">最佳实践</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>优先使用 transform 和 opacity（GPU 加速）</li>
              <li>避免同时动画化太多元素</li>
              <li>合理设置动画持续时间（200-500ms）</li>
              <li>使用适当的缓动函数</li>
              <li>清理不再需要的动画引用</li>
              <li>考虑用户的 prefers-reduced-motion 设置</li>
              <li>在动画完成后执行清理工作</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

// 类型定义
interface EasingFunction {
  name: string
  value: string
  description: string
}

// 响应式状态
const isSupported = ref(true)

// 基础动画
const basicBox = ref<HTMLElement | null>(null)
const basicAnimation = ref<Animation | null>(null)
const basicAnimState = ref('idle')
const basicAnimProgress = ref(0)
const basicPlaybackRate = ref(1)
const basicCurrentTime = ref(0)
let basicAnimationFrame: number | null = null

// 缓动函数
const easingFunctions = ref<EasingFunction[]>([
  { name: 'linear', value: 'linear', description: '线性，恒定速度' },
  { name: 'ease', value: 'ease', description: '默认，慢-快-慢' },
  { name: 'ease-in', value: 'ease-in', description: '慢速开始' },
  { name: 'ease-out', value: 'ease-out', description: '慢速结束' },
  { name: 'ease-in-out', value: 'ease-in-out', description: '慢-快-慢' },
  { name: 'cubic-bezier', value: 'cubic-bezier(0.68, -0.55, 0.265, 1.55)', description: '自定义贝塞尔曲线' }
])
const easingBoxes = ref<Record<string, HTMLElement>>({})

// 关键帧动画元素
const bounceBox = ref<HTMLElement | null>(null)
const spinBox = ref<HTMLElement | null>(null)
const pulseBox = ref<HTMLElement | null>(null)
const slideBox = ref<HTMLElement | null>(null)

// 序列动画
const sequenceBoxes = ref<HTMLElement[]>([])

// 路径动画
const pathCircle = ref<SVGCircleElement | null>(null)

// 交互动画
const hoverCard = ref<HTMLElement | null>(null)
const clickCard = ref<HTMLElement | null>(null)
const pressCard = ref<HTMLElement | null>(null)

// 粒子系统
const particleContainer = ref<HTMLElement | null>(null)
const activeParticles = ref(0)

// 复杂动画
const complexBox = ref<HTMLElement | null>(null)

// 文字动画
const textAnimation = ref<HTMLElement | null>(null)

// 统计
const totalAnimations = ref(0)
const runningAnimations = ref(0)
const finishedAnimations = ref(0)
const averageFrameRate = ref(60)

// 初始化
onMounted(() => {
  isSupported.value = !!(Element.prototype.animate)
  
  if (isSupported.value) {
    startBasicAnimation()
  }
})

// 清理
onUnmounted(() => {
  if (basicAnimationFrame) {
    cancelAnimationFrame(basicAnimationFrame)
  }
})

// 更新基础动画状态
const updateBasicAnimationState = () => {
  if (basicAnimation.value) {
    basicAnimState.value = basicAnimation.value.playState
    const duration = 2000
    const currentTime = basicAnimation.value.currentTime as number || 0
    basicAnimProgress.value = Math.round((currentTime / duration) * 100)
    basicPlaybackRate.value = basicAnimation.value.playbackRate
    basicCurrentTime.value = Math.round(currentTime)
  }

  basicAnimationFrame = requestAnimationFrame(updateBasicAnimationState)
}

// 开始基础动画
const startBasicAnimation = () => {
  if (!basicBox.value) return

  basicAnimation.value = basicBox.value.animate([
    { transform: 'translateX(0) rotate(0deg)', borderRadius: '8px' },
    { transform: 'translateX(200px) rotate(180deg)', borderRadius: '50%' },
    { transform: 'translateX(0) rotate(360deg)', borderRadius: '8px' }
  ], {
    duration: 2000,
    iterations: Infinity,
    easing: 'ease-in-out'
  })

  totalAnimations.value++
  runningAnimations.value++

  updateBasicAnimationState()
}

// 播放基础动画
const playBasicAnimation = () => {
  if (basicAnimation.value) {
    basicAnimation.value.play()
  } else {
    startBasicAnimation()
  }
}

// 暂停基础动画
const pauseBasicAnimation = () => {
  basicAnimation.value?.pause()
}

// 反向播放
const reverseBasicAnimation = () => {
  if (basicAnimation.value) {
    basicAnimation.value.playbackRate *= -1
  }
}

// 取消动画
const cancelBasicAnimation = () => {
  basicAnimation.value?.cancel()
  runningAnimations.value--
}

// 运行缓动函数对比
const runEasingComparison = () => {
  easingFunctions.value.forEach((easing) => {
    const element = easingBoxes.value[easing.name]
    if (element) {
      element.animate([
        { transform: 'translateX(0)' },
        { transform: 'translateX(calc(100% - 40px))' }
      ], {
        duration: 2000,
        easing: easing.value,
        fill: 'both'
      })
    }
  })

  totalAnimations.value += easingFunctions.value.length
}

// 弹跳动画
const runBounceAnimation = () => {
  if (!bounceBox.value) return

  bounceBox.value.animate([
    { transform: 'translateY(0)', offset: 0 },
    { transform: 'translateY(-100px)', offset: 0.4 },
    { transform: 'translateY(0)', offset: 0.6 },
    { transform: 'translateY(-50px)', offset: 0.8 },
    { transform: 'translateY(0)', offset: 1 }
  ], {
    duration: 1000,
    easing: 'ease-out'
  })

  totalAnimations.value++
}

// 旋转动画
const runSpinAnimation = () => {
  if (!spinBox.value) return

  spinBox.value.animate([
    { transform: 'rotate(0deg)' },
    { transform: 'rotate(360deg)' }
  ], {
    duration: 1000,
    easing: 'linear'
  })

  totalAnimations.value++
}

// 脉冲动画
const runPulseAnimation = () => {
  if (!pulseBox.value) return

  pulseBox.value.animate([
    { transform: 'scale(1)', opacity: 1 },
    { transform: 'scale(1.3)', opacity: 0.7 },
    { transform: 'scale(1)', opacity: 1 }
  ], {
    duration: 800,
    iterations: 3,
    easing: 'ease-in-out'
  })

  totalAnimations.value++
}

// 滑动动画
const runSlideAnimation = () => {
  if (!slideBox.value) return

  slideBox.value.animate([
    { transform: 'translateX(0)', opacity: 1 },
    { transform: 'translateX(100px)', opacity: 0 },
    { transform: 'translateX(-100px)', opacity: 0 },
    { transform: 'translateX(0)', opacity: 1 }
  ], {
    duration: 1500,
    easing: 'ease-in-out'
  })

  totalAnimations.value++
}

// 序列动画
const runSequenceAnimation = async () => {
  for (let i = 0; i < sequenceBoxes.value.length; i++) {
    const box = sequenceBoxes.value[i]
    if (box) {
      const animation = box.animate([
        { transform: 'scale(1) rotate(0deg)', backgroundColor: '#06b6d4' },
        { transform: 'scale(1.5) rotate(360deg)', backgroundColor: '#8b5cf6' },
        { transform: 'scale(1) rotate(0deg)', backgroundColor: '#06b6d4' }
      ], {
        duration: 500,
        easing: 'ease-in-out'
      })

      await animation.finished
      totalAnimations.value++
    }
  }
  finishedAnimations.value += sequenceBoxes.value.length
}

// 错峰动画
const runStaggerAnimation = () => {
  sequenceBoxes.value.forEach((box, index) => {
    if (box) {
      setTimeout(() => {
        box.animate([
          { transform: 'translateY(0)', opacity: 1 },
          { transform: 'translateY(-80px)', opacity: 0.5 },
          { transform: 'translateY(0)', opacity: 1 }
        ], {
          duration: 600,
          easing: 'ease-out'
        })
      }, index * 100)
    }
  })

  totalAnimations.value += sequenceBoxes.value.length
}

// 路径动画
const runPathAnimation = () => {
  if (!pathCircle.value) return

  pathCircle.value.animate([
    { cx: 50, cy: 200 },
    { cx: 200, cy: 50 },
    { cx: 400, cy: 200 },
    { cx: 600, cy: 50 },
    { cx: 750, cy: 200 }
  ], {
    duration: 3000,
    easing: 'ease-in-out'
  })

  totalAnimations.value++
}

// 圆形路径动画
const runCirclePathAnimation = () => {
  if (!pathCircle.value) return

  const centerX = 400
  const centerY = 200
  const radius = 150
  const steps = 60

  const keyframes = []
  for (let i = 0; i <= steps; i++) {
    const angle = (i / steps) * Math.PI * 2
    keyframes.push({
      cx: centerX + Math.cos(angle) * radius,
      cy: centerY + Math.sin(angle) * radius
    })
  }

  pathCircle.value.animate(keyframes, {
    duration: 3000,
    easing: 'linear'
  })

  totalAnimations.value++
}

// 卡片悬停
const onCardHover = () => {
  if (!hoverCard.value) return

  hoverCard.value.animate([
    { transform: 'translateY(0) scale(1)' },
    { transform: 'translateY(-10px) scale(1.05)' }
  ], {
    duration: 300,
    fill: 'forwards',
    easing: 'ease-out'
  })
}

const onCardLeave = () => {
  if (!hoverCard.value) return

  hoverCard.value.animate([
    { transform: 'translateY(-10px) scale(1.05)' },
    { transform: 'translateY(0) scale(1)' }
  ], {
    duration: 300,
    fill: 'forwards',
    easing: 'ease-out'
  })
}

// 卡片点击
const onCardClick = () => {
  if (!clickCard.value) return

  clickCard.value.animate([
    { transform: 'rotate(0deg)' },
    { transform: 'rotate(360deg)' }
  ], {
    duration: 600,
    easing: 'ease-in-out'
  })

  totalAnimations.value++
}

// 卡片按压
const onCardPress = () => {
  if (!pressCard.value) return

  pressCard.value.animate([
    { transform: 'scale(1)' },
    { transform: 'scale(0.95)' }
  ], {
    duration: 100,
    fill: 'forwards'
  })
}

const onCardRelease = () => {
  if (!pressCard.value) return

  pressCard.value.animate([
    { transform: 'scale(0.95)' },
    { transform: 'scale(1)' }
  ], {
    duration: 200,
    fill: 'forwards'
  })
}

// 创建粒子
const createParticles = (event: MouseEvent) => {
  if (!particleContainer.value) return

  const rect = particleContainer.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top

  const particleCount = 20
  const colors = ['#ef4444', '#f59e0b', '#10b981', '#3b82f6', '#8b5cf6']

  for (let i = 0; i < particleCount; i++) {
    const particle = document.createElement('div')
    particle.style.position = 'absolute'
    particle.style.left = x + 'px'
    particle.style.top = y + 'px'
    particle.style.width = '10px'
    particle.style.height = '10px'
    particle.style.borderRadius = '50%'
    particle.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)]
    particle.style.pointerEvents = 'none'

    particleContainer.value.appendChild(particle)
    activeParticles.value++

    const angle = (Math.PI * 2 * i) / particleCount
    const distance = 100 + Math.random() * 100
    const endX = x + Math.cos(angle) * distance
    const endY = y + Math.sin(angle) * distance

    const animation = particle.animate([
      { transform: 'translate(0, 0) scale(1)', opacity: 1 },
      { transform: `translate(${endX - x}px, ${endY - y}px) scale(0)`, opacity: 0 }
    ], {
      duration: 1000 + Math.random() * 500,
      easing: 'cubic-bezier(0, 0.5, 0.5, 1)'
    })

    animation.finished.then(() => {
      particle.remove()
      activeParticles.value--
      finishedAnimations.value++
    })

    totalAnimations.value++
  }
}

// 复杂动画 1
const runComplexAnimation1 = () => {
  if (!complexBox.value) return

  const animation1 = complexBox.value.animate([
    { transform: 'translate(-50%, -50%) scale(1) rotate(0deg)' },
    { transform: 'translate(-50%, -50%) scale(1.5) rotate(180deg)' },
    { transform: 'translate(-50%, -50%) scale(1) rotate(360deg)' }
  ], {
    duration: 2000,
    easing: 'ease-in-out'
  })

  const animation2 = complexBox.value.animate([
    { borderRadius: '8px' },
    { borderRadius: '50%' },
    { borderRadius: '8px' }
  ], {
    duration: 2000,
    easing: 'ease-in-out'
  })

  const animation3 = complexBox.value.animate([
    { boxShadow: '0 10px 30px rgba(0,0,0,0.3)' },
    { boxShadow: '0 30px 60px rgba(236,72,153,0.6)' },
    { boxShadow: '0 10px 30px rgba(0,0,0,0.3)' }
  ], {
    duration: 2000,
    easing: 'ease-in-out'
  })

  totalAnimations.value += 3
}

// 复杂动画 2
const runComplexAnimation2 = () => {
  if (!complexBox.value) return

  complexBox.value.animate([
    { transform: 'translate(-50%, -50%) skew(0deg, 0deg)' },
    { transform: 'translate(-50%, -50%) skew(10deg, 10deg)' },
    { transform: 'translate(-50%, -50%) skew(-10deg, -10deg)' },
    { transform: 'translate(-50%, -50%) skew(0deg, 0deg)' }
  ], {
    duration: 1500,
    iterations: 2,
    easing: 'ease-in-out'
  })

  totalAnimations.value++
}

// 复杂动画 3
const runComplexAnimation3 = () => {
  if (!complexBox.value) return

  complexBox.value.animate([
    { 
      transform: 'translate(-50%, -50%)',
      opacity: 1,
      filter: 'blur(0px) hue-rotate(0deg)'
    },
    { 
      transform: 'translate(-50%, -50%) translateY(-100px)',
      opacity: 0.5,
      filter: 'blur(5px) hue-rotate(180deg)'
    },
    { 
      transform: 'translate(-50%, -50%)',
      opacity: 1,
      filter: 'blur(0px) hue-rotate(360deg)'
    }
  ], {
    duration: 2000,
    easing: 'cubic-bezier(0.68, -0.55, 0.265, 1.55)'
  })

  totalAnimations.value++
}

// 文字动画
const runTextAnimation = (type: string) => {
  if (!textAnimation.value) return

  const text = textAnimation.value.textContent || ''
  textAnimation.value.innerHTML = ''

  const letters = text.split('').map((char, index) => {
    const span = document.createElement('span')
    span.textContent = char === ' ' ? '\u00A0' : char
    span.style.display = 'inline-block'
    textAnimation.value?.appendChild(span)
    return span
  })

  letters.forEach((letter, index) => {
    const delay = index * 50

    switch (type) {
      case 'wave':
        letter.animate([
          { transform: 'translateY(0)' },
          { transform: 'translateY(-20px)' },
          { transform: 'translateY(0)' }
        ], {
          duration: 600,
          delay,
          easing: 'ease-in-out'
        })
        break

      case 'bounce':
        letter.animate([
          { transform: 'translateY(0)' },
          { transform: 'translateY(-30px)' },
          { transform: 'translateY(0)' },
          { transform: 'translateY(-15px)' },
          { transform: 'translateY(0)' }
        ], {
          duration: 800,
          delay,
          easing: 'ease-out'
        })
        break

      case 'fade':
        letter.animate([
          { opacity: 0, transform: 'translateY(20px)' },
          { opacity: 1, transform: 'translateY(0)' }
        ], {
          duration: 500,
          delay,
          easing: 'ease-out'
        })
        break

      case 'scale':
        letter.animate([
          { transform: 'scale(0)' },
          { transform: 'scale(1.2)' },
          { transform: 'scale(1)' }
        ], {
          duration: 500,
          delay,
          easing: 'ease-out'
        })
        break
    }
  })

  totalAnimations.value += letters.length
}
</script>

<style scoped>
/* 动画样式 */
</style>

